package notes.java.juc.demo;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 线程池，以前启动一个线程总是new Thread方式，需要不停的创建与销毁线程，消耗资源。
 * 
 */
public class K13_TestThreadPoolCallable {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		// 创建一个线程池
		ExecutorService pool = Executors.newFixedThreadPool(10); // 创建固定大小的线程池
//		ExecutorService pool = Executors.newCachedThreadPool(); // 创建缓存缓和池，大小不固定
//		ExecutorService pool = Executors.newSingleThreadExecutor(); // 创建单一的线程池
		
		// 将任务放入到线程池中
		MyThread2 mythread = new MyThread2();
		for(int i=0;i<5;i++) {
			Future<String> result = pool.submit(mythread);
			System.out.println(result.get());
		}
		
		// 关闭线程池
		pool.shutdown();
	}
}

// 一个有返回值测试线程
class MyThread2 implements Callable<String> {
	@Override
	public String call() throws Exception {
		return Thread.currentThread().getName();
	}
}